package web.synchorichned;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author ZhangGJ
 * @Date 2022/02/07 13:57
 */
@Slf4j
@RestController
@RequestMapping("sync")
public class SynchronizedController4 {

    Map<String, Object> mutexCache = new ConcurrentHashMap<>();

    @GetMapping("process4")
    public String process(String orderId) {
        Object mutex4Key = mutexCache.computeIfAbsent(orderId, k -> new Object());
        synchronized (mutex4Key) {
            log.info("=======Start: {}", orderId);
            service(orderId);
            log.info("=======End: {}", orderId);
            mutexCache.remove(orderId);
        }
        return "Success!";
    }

    public void service(String orderId) {
        try {
            Thread.sleep(3000L);
            log.info("=====================执行了: {}", orderId);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
